package com.wjb.xietong.server.taskReply;

import org.json.JSONException;
import org.json.JSONObject;
import com.wjb.xietong.W3.HttpUtil;
import com.wjb.xietong.W3.JsonHttpResponseHandler;
import com.wjb.xietong.server.IRequestParam;
import com.wjb.xietong.server.IRequestResultListener;
import com.wjb.xietong.server.IService;
import com.wjb.xietong.util.IDs;
import com.wjb.xietong.util.LogD;

public class TaskFileUploadService implements IService{
	
	private long uniqueID = 0l;
	private TaskFileUploadParam param = null;
	private ITaskFileUploadListener listener = null;
	
	@Override
	public int request() {
		return HttpUtil.post(IDs.TASK_DETAIL_URL, param.parseData2Map(),
				new TaskFileUploadServiceListener());
	}
	
	public interface ITaskFileUploadListener {
		public abstract void requestSuccess(long requestUniqueID, String filePath);

		public abstract void requestFaield(long requestUniqueID, String errCode, String errMsg);
	}


	@Override
	public void setParameter(long uniqueID, IRequestResultListener listener,
			IRequestParam param) {
	}
	
	public void setParameter(long uniqueID, ITaskFileUploadListener listener,
			IRequestParam param){
		this.uniqueID = uniqueID;
		this.listener = listener;
		this.param = (TaskFileUploadParam) param;
	}
	
	public class TaskFileUploadServiceListener extends JsonHttpResponseHandler{

		@Override
		public void onSuccess(JSONObject response) {
			if(null != response){
				try {
					if(response.has(IDs.FILEPATH)){
						listener.requestSuccess(uniqueID, response.optString(IDs.FILEPATH));
					}else{
						if(response.has(IDs.ERROR_CODE)){
							if(!IDs.RESPONSE_CODE_000.equals(response.getString(IDs.ERROR_CODE))){
								listener.requestFaield(uniqueID, response.optString(IDs.ERROR_CODE),
										response.optString(IDs.ERROR_MSG));
							}else{
								listener.requestFaield(uniqueID, String.valueOf(IDs.HTTP_STATUS_SUCCESS),
										"文件上传失败");
							}
						}
					}
				} catch (JSONException e) {
					LogD.output("Exception:" + e.getMessage());
					listener.requestFaield(uniqueID, String.valueOf(IDs.HTTP_STATUS_SUCCESS),
							e == null ? "" : e.getMessage());
				}
			}
		}

		@Override
		public void onFailure(int errorCode, Throwable e,
				JSONObject errorResponse) {
			if (listener instanceof ITaskFileUploadListener) {
				listener.requestFaield(uniqueID, String.valueOf(errorCode),
						e == null ? "" : e.getMessage());
			}
		}
	}
}
